package com.ohuang.baseapp.eventbus;


import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;

class HandlerPoster extends EventHandler implements Poster {
    private final PendingPostQueue queue;
    private final Bus eventBus;
    private final int maxRunTime;
    private boolean handlerActive = false;

    HandlerPoster(EventRunner runner, Bus bus, int maxRunTime) {
        super(runner);
        this.eventBus = bus;
        this.maxRunTime = maxRunTime;
        queue = new PendingPostQueue();
    }

    @Override
    public void enqueue(Subscription subscription, Object event) {
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        synchronized (this) {
            queue.enqueue(pendingPost);
            if (!handlerActive) {
                handlerActive = true;
                sendEvent(0, Priority.IMMEDIATE);
            }
        }
    }


    @Override
    protected void processEvent(InnerEvent event) {
        boolean rescheduled = false;
        try {
            long started = System.currentTimeMillis();
            while (true) {
                PendingPost pendingPost = queue.poll();
                if (pendingPost == null) {
                    synchronized (this) {
                        // Check again, this time in synchronized
                        pendingPost = queue.poll();
                        if (pendingPost == null) {
                            handlerActive = false;
                            return;
                        }
                    }
                }
                eventBus.invokeSubscriber(pendingPost);
                long timeInMethod = System.currentTimeMillis() - started;
                if (timeInMethod >= maxRunTime) {
                    sendEvent(0, Priority.IMMEDIATE);
                    rescheduled = true;
                    return;
                }
            }
        } finally {
            handlerActive = rescheduled;
        }
    }

}
